package com.wy.controller.wy;

import com.wy.bean.HouseBean;
import com.wy.constants.CommonValues;
import com.wy.model.sys.PageResult;
import com.wy.model.sys.UserEntity;
import com.wy.service.sys.UserService;
import com.wy.service.wy.HouseService;
import com.wy.utils.BaseResponseInfo;
import com.wy.utils.ConstantData;
import com.wy.utils.FileUtil;
import com.wy.utils.HTTPStatus;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Auther: tracy
 * @Date: 2018/8/20 16:58
 * @Description: 房屋管理
 */
@RestController
public class HouseController {
	private Logger log = LoggerFactory.getLogger(HouseController.class);

	@Resource(name = "houseServiceImpl")
	private HouseService houseService;
	@Resource(name = "userServiceImpl")
	private UserService userService;
	@Autowired
	private CommonValues commonValues;


	/**
	 * 获取房屋表数据
	 * 
	 * @param pageSize
	 * @param page
	 * @return
	 */
	@GetMapping("/houses")
	public PageResult householdList(HttpServletRequest request, Integer pageSize, Integer page,Integer buildingId,String houseCode,Integer residenceId) {
		List<String> rids = new ArrayList<>();
		UserEntity userEntity = userService.getUserByLoginName(request.getUserPrincipal().getName());
		if(null != userEntity) {
			String rid = userEntity.getRid();
			if(!StringUtils.isEmpty(rid)){

				List list = Arrays.asList(rid.split(","));
				rids = new ArrayList(list);
			}
		}
		PageResult pageResult = new PageResult();
		if("admin".equals(userEntity.getLoginName())) {
			rids = null;
		}else {
			rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
		}
		pageResult.setData(houseService.houseList(pageSize, page * pageSize, buildingId, houseCode,rids,residenceId));
		pageResult.setTotalCount(houseService.houseSize(pageSize, page * pageSize, buildingId, houseCode,rids,residenceId));
		log.debug("The method is ending");
		return pageResult;
	}

	/**
	 * 新建房屋信息
	 * @param houseEntity
	 * @return
	 */
	@PostMapping("/houses/house")
	public HouseBean insertMenu(@RequestBody HouseBean houseEntity) {
		houseService.insertHouse(houseEntity);
		log.debug("The method is ending");
		return houseEntity;
	}

	/**
	 * 修改房屋信息
	 * 
	 * @param houseEntity
	 * @param id
	 * @return
	 */
	@PutMapping("/houses/{id}")
	public HouseBean updateMenu(@RequestBody HouseBean houseEntity, @PathVariable int id) {
		if (houseEntity.getId() == id) {
			houseService.updateHouse(houseEntity);
		}
		log.debug("The method is ending");
		return houseEntity;
	}

	/**
	 * 删除房屋信息
	 * 
	 * @param groupId
	 * @return
	 */
	@DeleteMapping("/houses")
	public void deleteMenus(@RequestBody List<String> groupId) {
		houseService.deleteHouses(groupId);
	}

	/**
	 * 添加房屋信息（无登录验证）
	 * @param houseEntity
	 * @return
	 */
	@ResponseBody
	@PostMapping("/save_house")
	public BaseResponseInfo saveHouse(@RequestBody HouseBean houseEntity) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			houseService.insertHouse(houseEntity);
			baseResponseInfo.code = HTTPStatus.OK;
			data.put("message", ConstantData.MSG_SUCCESS_INFO);
		} catch (Exception ex){
			ex.printStackTrace();
			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
		}
		baseResponseInfo.data = data;
		return baseResponseInfo;
	}


	/**
	 * 查询房屋信息（无验证）
	 * @param pageSize
	 * @param start
	 * @return
	 */
//	@ResponseBody
//	@GetMapping("/get_house_list")
//	public BaseResponseInfo getHouseholdList(@RequestParam("pageSize") int pageSize, @RequestParam("start")int start) {
//		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
//		Map<String, Object> data = new HashMap<String, Object>();
//		try {
//			data.put("houses", houseService.houseList("",pageSize, (start -1)* pageSize,null,null,null,null));
//			data.put("count", houseService.houseSize(pageSize, (start -1) * pageSize,null,null,null,null));
//			baseResponseInfo.code = HTTPStatus.OK;
//			data.put("message", ConstantData.MSG_SUCCESS_INFO);
//		}catch(Exception ex){
//			ex.printStackTrace();
//			baseResponseInfo.code = HTTPStatus.INTERNAL_SERVER_ERROR;
//		}
//		baseResponseInfo.data = data;
//		return baseResponseInfo;
//	}

	/**
	 * 根据楼栋id获取房屋
	 * @return
	 */
	@GetMapping("/getHouseByBuildingId")
	public BaseResponseInfo getHousesByBuildingId(Integer buildingID) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		baseResponseInfo.data = houseService.getHousesByBuildingId(buildingID);
		log.debug("The method is ending");
		return baseResponseInfo;
	}

	@RequestMapping("/houses/download")
	public void download(HttpServletRequest request, HttpServletResponse response,
						 Integer buildingId,String houseCode,Integer residenceId,String username) throws Exception {
		response.setHeader("content-Type", "application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "attachment;filename="+new String( "房屋信息.xls".getBytes("gb2312"), "ISO8859-1" ));

		List<String> rids = new ArrayList<>();
		UserEntity userEntity = userService.getUserByLoginName(username);
		if(null != userEntity) {
			String rid = userEntity.getRid();
			if(!StringUtils.isEmpty(rid)){
				List list = Arrays.asList(rid.split(","));
				rids = new ArrayList(list);
			}
		}
		List<HouseBean> list = new ArrayList<>();
		if("admin".equals(username)) {
			rids = null;
		}else {
			rids.add("-1");//手动添加-1，如果当前登录用户无权限，则区别于admin的用户，查不到数据
		}
		list = houseService.houseList(null, null, buildingId, houseCode, rids, residenceId);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), HouseBean.class, list);
		workbook.write(response.getOutputStream());
	}

	/**
	 * 数据导入
	 * @param file
	 */
	@PostMapping("/houses/import")
	public Map<String,String> importExcel(MultipartFile file){

		Map<String,String> map = FileUtil.judgeRepeatExcel(file,5,1);
		if(map.isEmpty()) {
			List<HouseBean> houseList = FileUtil.importExcel(file, 0, 1, HouseBean.class);
			System.out.println("导入数据一共【" + houseList.size() + "】行");
			if (houseList != null) {
				List<HouseBean> temp = houseService.getHouseListImport(houseList);
				if (temp.size() == 0) {
					houseService.insertBatch(houseList);
				} else {
					for (HouseBean hb : temp) {
						map.put(String.valueOf(hb.getId()), hb.getHouseCode());
					}
				}
			}
		}
		return map;

	}

	@GetMapping("/houses/getUnitByBuildingId")
	public BaseResponseInfo getUnitByBuildingId(Integer buildingId){
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		baseResponseInfo.data = houseService.getUnitByBuildingId(buildingId);
		return baseResponseInfo;
	}

	@GetMapping("/houses/getHousesByBidUnit")
	public BaseResponseInfo getHousesByBidUnit(Integer buildingId,String unitName){
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		baseResponseInfo.data = houseService.getHousesByBidUnit(buildingId,unitName);
		return baseResponseInfo;
	}

}
